/**
 * 
 */
package threads;

import java.util.Stack;

/**
 * @author michele
 *
 */
public class MyThread extends Thread {
	
	public static final long INFINITE_WAIT_TIME = 900000000;
	
	protected Stack<Integer> localMBox;
	protected long cycleLength_msec = 1000;
	protected MyThreadsOperations thread;
	protected boolean hasToStop = false;
	

	/**
	 * 
	 */
	public MyThread(Stack<Integer> mBox) {
		localMBox = mBox;
	}
		
	public void stopMyThread(){
		hasToStop = true;
		this.interrupt();
	}
	
	public void sleepThread(){
		System.out.println("suspended "+this.getName());
		cycleLength_msec = INFINITE_WAIT_TIME;
	}
	
	public MyThread(Stack<Integer> localMBox, long cycleLengthMsec,
			boolean hasToStop) {
		super();
		this.localMBox = localMBox;
		cycleLength_msec = cycleLengthMsec;
		this.hasToStop = hasToStop;
	}

	public boolean setThreadOperations(MyThreadsOperations ope){
		thread = ope;
		return true;
	}
	
	public void run(){
		boolean running = true;
		while(running){
			try {
				//sleep(cycleLength_msec);
				//wait();
				sleep(cycleLength_msec);
				synchronized (localMBox) {
//					localMBox.wait(cycleLength_msec);
					thread.threadOperations();
					localMBox.notify();
				}
			} catch (InterruptedException e) {
				//				e.printStackTrace();
				if(hasToStop){
					running = false;
					System.out.println(getName()+ " I'm interrupted");
					System.out.println("Stack length is: "+localMBox.size());
				}
			}				
		}
	}

	/**
	 * @param target
	 */
	public MyThread(Runnable target) {
		super(target);
	}

	/**
	 * @param name
	 */
	public MyThread(String name) {
		super(name);
	}

	/**
	 * @param group
	 * @param target
	 */
	public MyThread(ThreadGroup group, Runnable target) {
		super(group, target);
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param group
	 * @param name
	 */
	public MyThread(ThreadGroup group, String name) {
		super(group, name);
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param target
	 * @param name
	 */
	public MyThread(Runnable target, String name) {
		super(target, name);
	}

	/**
	 * @param group
	 * @param target
	 * @param name
	 */
	public MyThread(ThreadGroup group, Runnable target, String name) {
		super(group, target, name);
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param group
	 * @param target
	 * @param name
	 * @param stackSize
	 */
	public MyThread(ThreadGroup group, Runnable target, String name,
			long stackSize) {
		super(group, target, name, stackSize);
		// TODO Auto-generated constructor stub
	}

}
